package com.xspace.android.xafcommon.db.dbsub;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

import com.xspace.android.xafcommon.been.OfflineWorkLogBean;
import com.xspace.android.xafcommon.db.BaseSql;
import com.xspace.android.xafcommon.util.LogUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 离线工作日志
 *
 * @author Administrator
 */
public class OfflineWorkLogDB extends BaseSql {
    //logid即为插入时间的毫秒值,insertTime为带格式的日期,而非毫秒值
    private final String LogId = "logid";
    private final String LogJSContent = "jscontent";
    /**
     * 2017.3.3 将该字段作为日志类别,用于区分是编辑日志还是提交日志0: 提交日志 1: 编辑日志
     */
    private final String LogContent = "content";
    private final String InsertTime = "inserttime";
    /**
     * userid
     **/
    private final String ReMark0 = "remark0";
    /**
     * 失败次数
     */
    private final String ReMark1 = "remark1";
    private final String Object = "object";
    private String TableName = "OfflineWorkLog";
    private MyDBHelper helpDb;
    private SQLiteDatabase sqldb;
    private String tag = "OfflineWorkLogDB";

    @Override
    public void create(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE " + TableName + " (_ID INTEGER PRIMARY KEY AUTOINCREMENT," +
                LogId + " integer64," +
                LogJSContent + " text," +
                LogContent + " text," +
                InsertTime + " text," +
                ReMark0 + " text," +
                ReMark1 + " text," +
                Object + " text);");

    }

    public OfflineWorkLogDB() {

    }

    public void dropTable(SQLiteDatabase db) {
        db.execSQL("DROP TABLE IF EXISTS " + TableName);
    }

    public OfflineWorkLogDB(MyDBHelper db) {
        super(db);
        helpDb = db;
    }

    @Override
    public void upgrade(SQLiteDatabase arg0) {
        // TODO Auto-generated method stub

    }

    private void openDB() {
        helpDb.open();
        sqldb = helpDb.mDatabase;

    }

    private SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public void insertOrUpdate(String json, String object, String content, long insertTime, String userid) {
        if (TextUtils.isEmpty(json))
            return;
        String insertTimeStr = df.format(new Date(insertTime));
        openDB();
        ContentValues cv = new ContentValues();
        String[] columns = {LogId, LogJSContent, InsertTime};
        String selection = InsertTime + "=? and " + ReMark0 + "=?";
        String[] selectionArgs = new String[]{insertTimeStr, userid};
        Cursor cur = sqldb.query(TableName, columns, selection, selectionArgs, null, null, null);
        if (cur != null && cur.getCount() > 0) {
            cv.put(LogJSContent, json);
            cv.put(Object, object);
            sqldb.update(TableName, cv, selection, selectionArgs);
            LogUtil.v(tag, "insertOrUpdate update>>>" + object + " item:" + LogJSContent);
        } else {
            cv.put(LogId, insertTime);
            cv.put(InsertTime, insertTimeStr);
            cv.put(LogJSContent, json);
            cv.put(LogContent, content);
            cv.put(Object, object);
            cv.put(ReMark0, userid);
            long result = sqldb.insert(TableName, null, cv);
            LogUtil.v(tag, "insertOrUpdate insert>>>InsertTime:" + insertTimeStr + " ObjectName:" + object
                    + " LogContent:" + content + " result:" + result + "useid:" + userid);
        }
        closeDbAndCursor(cur);
    }

    public void closeDbAndCursor(Cursor cursor) {
        if (cursor != null) {
            cursor.close();
            cursor = null;
        }
        /*
         * if (db != null) { db.close(); db = null; }
		 */
    }

    public OfflineWorkLogBean queryBeanByLogId(String time) {
        openDB();
        OfflineWorkLogBean logb = null;
        String selection = LogId + "=?";
        String[] selectionArgs = new String[]{time};
        String[] columns = {LogContent, LogJSContent, InsertTime, Object, ReMark0, LogId};
        Cursor cur = sqldb.query(TableName, columns, selection, selectionArgs, null, null, null);
        if (cur != null && cur.getCount() > 0) {
            if (cur.moveToFirst()) {
                String content = cur.getString(0);
                String jscontent = cur.getString(1);
                String inserttime = cur.getString(2);
                String object = cur.getString(3);
                String userid0 = cur.getString(4);
                String logId = cur.getString(5);
                LogUtil.v(tag, "queryAllData >>>InsertTime:" + inserttime + " ObjectName:" + object + " LogContent:"
                        + content + " >>userid:" + userid0);
                logb = new OfflineWorkLogBean(inserttime, jscontent, content, object);
                logb.logid = logId;

            }
        }
        cur.close();
        return logb;
    }

    public List<OfflineWorkLogBean> queryAllData(String userid) {
        List<OfflineWorkLogBean> list = new ArrayList<OfflineWorkLogBean>();
        openDB();
        String selection = ReMark0 + "=?";
        String[] selectionArgs = new String[]{userid};
        String[] columns = {LogContent, LogJSContent, InsertTime, Object, ReMark0, LogId};
        Cursor cur = sqldb.query(TableName, columns, selection, selectionArgs, null, null, null);
        if (cur != null && cur.getCount() > 0) {
            while (cur.moveToNext()) {
                String jscontent = cur.getString(1);
                String content = cur.getString(0);
                String inserttime = cur.getString(2);
                String object = cur.getString(3);
                String userid0 = cur.getString(4);
                String logId = cur.getString(5);
                LogUtil.v(tag, "queryAllData >>>InsertTime:" + inserttime + " ObjectName:" + object + " LogContent:"
                        + content + " >>userid:" + userid0 + " logId " + logId);
                OfflineWorkLogBean logb = new OfflineWorkLogBean(inserttime, jscontent, content, object);
                logb.logid = logId;
                list.add(logb);
            }
        }
        cur.close();
        LogUtil.v(tag, "queryAllData count:" + list.size() + " userid:" + userid);
        return list;
    }

    public OfflineWorkLogBean queryLatestOneData(String userid) {
        OfflineWorkLogBean bean = null;
        openDB();
        String selection = ReMark0 + "=?";
        String[] selectionArgs = new String[]{userid};
        String[] columns = {LogContent, LogJSContent, InsertTime, Object, ReMark0, ReMark1, LogId};
        Cursor cur = sqldb.query(TableName, columns, selection, selectionArgs, null, null, null);
        if (cur != null && cur.getCount() > 0) {
            if (cur.moveToFirst()) {
                String content = cur.getString(0);
                String jscontent = cur.getString(1);
                String inserttime = cur.getString(2);
                String object = cur.getString(3);
                String userid0 = cur.getString(4);
                String count = cur.getString(5);
                String logId = cur.getString(6);
                LogUtil.v(tag, "queryLatestOneData >>>InsertTime:" + inserttime + " ObjectName:" + object
                        + " LogContent:" + content + " >>userid:" + userid0 + "count " + count);
                if (TextUtils.isEmpty(count)) {
                    count = 0 + "";
                }
                bean = new OfflineWorkLogBean(inserttime, jscontent, content, object);
                bean.logid = logId;
                bean.failedCount = Integer.parseInt(count);
            }
        }
        cur.close();
        LogUtil.v(tag, "queryLatestOneData bean:" + (bean == null));
        return bean;
    }

    public OfflineWorkLogBean queryLastLogDataCount(String userid) {
        OfflineWorkLogBean bean = null;
        openDB();
        String sql = "select " + LogContent + "," + LogJSContent + "," + InsertTime + "," + Object + "," + ReMark0 +
                "," + ReMark1 + "," + LogId +
                " from OfflineWorkLog where  remark1 is null   and " + ReMark0 + " = '" + userid + "'" +
                " UNION\n" +
                "select " + LogContent + "," + LogJSContent + "," + InsertTime + "," + Object + "," + ReMark0 + "," +
                ReMark1 + "," + LogId
                + " from OfflineWorkLog where  remark1  < 4 and " + ReMark0 + "=  '" + userid + "'";
        LogUtil.d(sql);
        Cursor cur = sqldb.rawQuery(sql, null);
//        String selection = ReMark0 + "=? and " + ReMark1 + " ";
//        String[] selectionArgs = new String[]{userid};
//        String[] columns = {};
//     = sqldb.query(TableName, columns, selection, selectionArgs, null, null, null);
        if (cur != null && cur.getCount() > 0) {
            if (cur.moveToFirst()) {
                String content = cur.getString(0);
                String jscontent = cur.getString(1);
                String inserttime = cur.getString(2);
                String object = cur.getString(3);
                String userid0 = cur.getString(4);
                String count = cur.getString(5);
                String logId = cur.getString(6);
                LogUtil.v(tag, "queryLatestOneData >>>InsertTime:" + inserttime + " ObjectName:" + object
                        + " LogContent:" + content + " >>userid:" + userid0 + "count " + count);
                if (TextUtils.isEmpty(count)) {
                    count = 0 + "";
                }
                bean = new OfflineWorkLogBean(inserttime, jscontent, content, object);
                bean.logid = logId;
                bean.failedCount = Integer.parseInt(count);
            }
        }
        cur.close();
        LogUtil.v(tag, "queryLatestOneData bean:" + (bean == null));
        return bean;
    }

    public void deleteOneData(String insertTime, String userid) {
        openDB();
        String whereClause = InsertTime + "=? and " + ReMark0 + "=?";
        String[] whereArgs = new String[]{insertTime, userid};
        int result = sqldb.delete(TableName, whereClause, whereArgs);
        LogUtil.v(tag, "DeleteOneData insertTime:" + insertTime + " result:" + result + " userid:" + userid);
    }

    public int deleteOneData(String logId) {
        openDB();
        String whereClause = LogId + "=? ";
        String[] whereArgs = new String[]{logId};
        int result = sqldb.delete(TableName, whereClause, whereArgs);
        LogUtil.v(tag, "DeleteOneData logId:" + logId + " result:" + result);
        return result;
    }

    public void updateCommitNumber(String insertTime, String userid) {
        openDB();
        String[] columns = {ReMark1};
        String selection = InsertTime + "=? and " + ReMark0 + "=?";
        String[] selectionArgs = new String[]{insertTime, userid};
        Cursor cur = sqldb.query(TableName, columns, selection, selectionArgs, null, null, null);
        String count = "";
        if (cur != null && cur.getCount() > 0) {
            while (cur.moveToNext()) {
                count = cur.getString(0);
            }
        }
        cur.close();
        if (TextUtils.isEmpty(count)) {
            count = "0";
        }
        count = Integer.parseInt(count) + 1 + "";
        if (Integer.parseInt(count) > 3) {
            //删除
            deleteOneData(insertTime, userid);
        } else {
            openDB();
            String whereClause = InsertTime + "=? and " + ReMark0 + "=?";
            String[] whereArgs = new String[]{insertTime, userid};
            ContentValues cv = new ContentValues();
            cv.put(ReMark1, count);
            int result = sqldb.update(TableName, cv, whereClause, whereArgs);
            LogUtil.v(tag, "updateCommitNumber insertTime:" + insertTime + " result:" + result + " userid:" + userid
                    + "count:" + count);
        }
    }

    public void updateCommitNumberByLogId(String logid, String userid) {
        openDB();
        String[] columns = {ReMark1};
        String selection = LogId + "=? and " + ReMark0 + "=?";
        String[] selectionArgs = new String[]{logid, userid};
        Cursor cur = sqldb.query(TableName, columns, selection, selectionArgs, null, null, null);
        String count = "";
        if (cur != null && cur.getCount() > 0) {
            while (cur.moveToNext()) {
                count = cur.getString(0);
            }
        }
        cur.close();
        if (TextUtils.isEmpty(count)) {
            count = "0";
        }
        count = Integer.parseInt(count) + 1 + "";
//        if (Integer.parseInt(count) > 3) {
//            //删除
////            deleteOneData(logid);
//        } else {
        openDB();
        String whereClause = LogId + "=? and " + ReMark0 + "=?";
        String[] whereArgs = new String[]{logid, userid};
        ContentValues cv = new ContentValues();
        cv.put(ReMark1, count);
        int result = sqldb.update(TableName, cv, whereClause, whereArgs);
        LogUtil.v(tag, "updateCommitNumber insertTime:" + logid + " result:" + result + " userid:" + userid
                + "count:" + count);
//        }
    }

}
